const log4js = require('../../../utils/log4js');
const request = require('request-promise-any');

const configure = require('little-man-config');
const loginCfg = configure.get('thirdLogin');

const thirdLogin = module.exports;

// 获取qq授权网址
thirdLogin.qqAuthPage = async () => {
    return `https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=${loginCfg.qq.appid}&redirect_uri=${loginCfg.qq.redirect_uri}&scope=${loginCfg.qq.scope}&state=QQ`;
};

// 获取qq登录用户的信息
thirdLogin.getQQUserInfo = async (code, state, req) => {
    if (!code || !state) throw new Error('参数错误');

    // 捕获报错
    try {
        let accessTokenUrl = `https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=${loginCfg.qq.appid}&client_secret=${loginCfg.qq.appkey}&code=${code}&state=${state}&redirect_uri=${loginCfg.qq.redirect_uri}`;
        let accessTokenRet = await request.get(accessTokenUrl);

        let accessTokenArr = accessTokenRet.split('&')[0];
        let access_token = accessTokenArr.split('=')[1];
        let openIdUrl = `https://graph.qq.com/oauth2.0/me?access_token=${access_token}`;
        let openIdRet = await request.get(openIdUrl);

        let openIdRegex = /"openid":"(\w+)"/;
        let openid = openIdRet.match(openIdRegex)[1];

        //拿到openid， 数据库查询用户是否存在
        let userRet = await helper.getRow(db().md_user, {qq_id: openid}, null, {exclude: ['password', 'wx_id', 'qq_id']});

        if (userRet) {
            req.session.client_login_info = userRet;
            return {userInfo: userRet, hasAuth: true}
        } else {
            let getUSerInfoUrl = `https://graph.qq.com/user/get_user_info?access_token=${access_token}&oauth_consumer_key=${loginCfg.qq.appid}&openid=${openid}`;
            let userInfoRet = await request.get(getUSerInfoUrl);
            userInfoRet = JSON.parse(userInfoRet.replace(/\n/gi,''));
            userInfoRet.openid = openid;
            userInfoRet.headimgurl = userInfoRet.figureurl_2;
            if(userInfoRet.gender == '男') {
                userInfoRet.sex = 1;
            } else if(userInfoRet.gender == '女'){
                userInfoRet.sex = 2;
            } else {
                userInfoRet.sex = 0;
            }
            userInfoRet.userType='qq';

            return {userInfo: userInfoRet, openid: openid, hasAuth: false};
        }
    } catch (e) {
        console.log(e);
        throw new Error(e.message);
    }

};

// 获取微信登录授权网址
thirdLogin.wechatAuthPage = async () => {
    return `https://open.weixin.qq.com/connect/qrconnect?appid=${loginCfg.wechat.appid}&redirect_uri=${encodeURIComponent(loginCfg.wechat.redirect_uri)}&response_type=code&scope=${loginCfg.wechat.scope}&state=WECHAT#wechat_redirect`
};

// 获取微信登录用户信息
thirdLogin.getWechatUserInfo = async (code, state, req) => {
    if (!code || !state) throw new Error('参数错误');

    try {
        let accessTokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${loginCfg.wechat.appid}&secret=${loginCfg.wechat.appsecret}&code=${code}&grant_type=authorization_code`;
        let accessTokenRet = await request.get(accessTokenUrl);

        accessTokenRet = JSON.parse(accessTokenRet);
        let {access_token, openid} = accessTokenRet;


        //拿到openid， 数据库查询用户是否存在
        let openidRet = await helper.getRow(db().md_user, {wx_id: openid}, null, {exclude: ['password', 'wx_id', 'qq_id']});
        if (openidRet) {
            req.session.client_login_info = openidRet;
            return {userInfo: openidRet, hasAuth: true}
        } else {
            let userInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`;
            let userInfoRet = await request.get(userInfoUrl);
            userInfoRet = JSON.parse(userInfoRet);
            userInfoRet.userType='wx';

            return {userInfo: userInfoRet, openid: openid, hasAuth: false};
        }
    } catch (e) {
        console.log(e);
        throw new Error(e.message);
    }
};

thirdLogin.getUserInfo = async (code, state, req) => {
    if (!code || !state) throw new Error('参数错误');

    if (state.toLowerCase() === 'qq') {
        return await thirdLogin.getQQUserInfo(code, state, req);
    } else if (state.toLowerCase() == 'wechat') {
        return await thirdLogin.getWechatUserInfo(code, state, req);
    } else {
        throw new Error('no type error');
    }
};